package com.xh.bussiness.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.tiku.bean.request.QuestionCollectRequest;
import com.xh.bussiness.tiku.dao.QuestionCollectMapper;
import com.xh.bussiness.tiku.model.QuestionCollect;
import com.xh.bussiness.tiku.service.IQuestionCollectService;
import com.xh.core.bean.XhPage;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionCollectImpl extends BaseServiceImpl<QuestionCollectMapper, QuestionCollect> implements IQuestionCollectService {

    @Autowired
    private QuestionCollectMapper questionCollectMapper;

    @Override
    public XhPage<QuestionCollect> queryPage(XhPage page, QuestionCollectRequest bean) throws Exception {
        QueryWrapper qw=new QueryWrapper<QuestionCollect>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public Integer addQuestionCollect(QuestionCollectRequest bean) {
        QuestionCollect  questionCollect = new QuestionCollect();
        BeanUtils.copyProperties(bean,questionCollect);
        return this.dao.insert(questionCollect);
    }

    @Override
    public String deleteQuestionCollect(String id) {
        QuestionCollect questionCollect = this.getById(id);
        if (questionCollect == null) {
            return "当前试题收藏不存在";
        }
        this.dao.deleteById(id);
        return  null;
    }

    @Override
    public List<QuestionCollect> queryQuestionCollect(QuestionCollectRequest bean) {
        QueryWrapper qw = new QueryWrapper<QuestionCollect>();
//		// 拼装条件
        qw = prepareParams(bean, qw);
//
        return this.dao.selectList(qw);
    }

    @Override
    public String cancelCollect(QuestionCollectRequest bean) {
        QueryWrapper qw = new QueryWrapper<QuestionCollect>();
        qw = prepareParams(bean, qw);
        List<QuestionCollect> list = this.dao.selectList(qw);
        if(list.isEmpty()){
            return "当前试题没有收藏";
        }
        this.dao.delete(qw);
        return null;
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(QuestionCollectRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(!StringUtils.isEmpty(bean.getQuestionId())){
            qw.eq("question_id",bean.getQuestionId());
        }
        if(!StringUtils.isEmpty(bean.getUserId())){
            qw.eq("user_id",bean.getUserId());
        }
        return qw;
    }
}
